package com.example.mydy;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mydy.api.UserApi;
import com.example.mydy.utils.NetworkUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_TOKEN = "token";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_USER_TYPE = "userType";
    private static final String KEY_USER_NICKNAME = "userNickname";
    private static final String KEY_BALANCE = "balance";
    private static final String KEY_LEVEL = "level";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    private static final String KEY_EMAIL = "email";

    private static final String USER_TYPE_ADMIN = "admin";
    private static final String USER_TYPE_USER = "user";

    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private ProgressBar progressBar;
    private TextView tvRegister;

    private boolean isNavigating = false;
    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: LoginActivity创建");
        
        NetworkUtils.setBaseUrl("http://106.52.82.133:3000/");
        NetworkUtils.initRetrofit();
        userApi = NetworkUtils.getUserApi();
        
        setContentView(R.layout.activity_login);
        Log.d(TAG, "当前使用的API地址: " + NetworkUtils.getCurrentBaseUrl());
        
        initViews();
        loadRememberedCredentials();
        checkAutoLogin();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: LoginActivity销毁");
    }

    private void login() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etUsername.getWindowToken(), 0);

        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        progressBar.setVisibility(View.VISIBLE);
        btnLogin.setEnabled(false);

        userApi.login(username, password).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                progressBar.setVisibility(View.GONE);
                btnLogin.setEnabled(true);

                if (response.isSuccessful() && response.body() != null) {
                    LoginResponse loginResponse = response.body();

                    if (loginResponse.isSuccess()) {
                        Log.d(TAG, "登录成功: " + loginResponse.getMessage());
                        Log.d(TAG, "令牌: " + (loginResponse.getToken() != null ?
                                loginResponse.getToken().substring(0, Math.min(20, loginResponse.getToken().length())) + "..." : "null"));

                        handleLoginSuccess(loginResponse);
                    } else {
                        String errorMessage = loginResponse.getMessage();
                        Log.d(TAG, "登录失败: " + errorMessage);
                        Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.d(TAG, "登录HTTP错误: " + response.code());
                    Log.d(TAG, "错误信息: " + NetworkUtils.getResponseErrorMessage(response));
                    Toast.makeText(LoginActivity.this, "登录失败: " + NetworkUtils.getResponseErrorMessage(response), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                btnLogin.setEnabled(true);

                Log.e(TAG, "登录请求失败", t);
                String errorMessage = NetworkUtils.getErrorMessage(t);
                Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean isLoggedIn() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean loggedIn = prefs.getBoolean(KEY_IS_LOGGED_IN, false);
        String token = NetworkUtils.getAuthToken(this);

        boolean validLogin = loggedIn && token != null && !token.isEmpty();
        Log.d(TAG, "是否已登录: " + validLogin + ", isLoggedIn=" + loggedIn +
                ", token存在=" + (token != null && !token.isEmpty()));
        return validLogin;
    }

    private void saveLoginInfo(LoginResponse response) {
        if (response == null) {
            Log.e(TAG, "无法保存登录信息：响应为空");
            return;
        }

        String userId = String.valueOf(response.getUserId());
        String username = response.getUsername();
        String userType = response.getUserType();
        String token = response.getToken();

        Log.d(TAG, "保存登录信息: userId=" + userId + ", username=" + username +
                ", userType=" + userType + ", token=" + (token != null ? "非空" : "空"));

        if (token == null || token.isEmpty()) {
            Log.e(TAG, "令牌为空，无法完成登录");
            Toast.makeText(this, "登录失败：服务器未返回有效令牌", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences tokenPrefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE);
        tokenPrefs.edit().putString(KEY_TOKEN, token).commit();

        NetworkUtils.saveAuthToken(this, token);

        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.putString(KEY_USER_ID, userId);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_USER_TYPE, userType);
        editor.putString(KEY_USER_NICKNAME, response.getUserNickname());

        boolean saved = editor.commit();
        Log.d(TAG, "登录信息保存" + (saved ? "成功" : "失败"));

        String savedToken = NetworkUtils.getAuthToken(this);
        Log.d(TAG, "验证保存的令牌: " + (savedToken != null && savedToken.equals(token) ? "正确" : "不匹配"));

        editor.commit();

        try {
            if (!NetworkUtils.validateToken(this, token)) {
                Log.e(TAG, "令牌验证失败");
                Toast.makeText(this, "令牌验证失败，请重新登录", Toast.LENGTH_SHORT).show();
                clearLoginInfo();
                return;
            }
        } catch (Exception e) {
            Log.e(TAG, "令牌验证异常: " + e.getMessage());
            Toast.makeText(this, "令牌验证异常，请重新登录", Toast.LENGTH_SHORT).show();
            clearLoginInfo();
            return;
        }
    }

    private void clearLoginInfo() {
        SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
        editor.putBoolean(KEY_IS_LOGGED_IN, false);
        editor.putString(KEY_TOKEN, "");
        editor.putString(KEY_USER_TYPE, "");
        editor.commit();
        NetworkUtils.clearAuthToken(this);
    }

    private void handleLoginSuccess(LoginResponse response) {
        Log.d(TAG, "登录成功，准备保存用户信息并导航. UserType=" + response.getUserType());
        Log.d(TAG, "登录成功信息. Username=" + response.getUsername() + ", UserId=" + response.getUserId() + ", UserNickname=" + response.getUserNickname());

        if (isNavigating) {
            Log.d(TAG, "handleLoginSuccess: 已在导航过程中，避免重复操作");
            return;
        }

        isNavigating = true;

        String userType = response.getUserType();
        Intent intent;

        if ("admin".equalsIgnoreCase(userType)) {
            Log.d(TAG, "导航到管理员页面");
            intent = new Intent(LoginActivity.this, AdminActivity.class);
        } else {
            Log.d(TAG, "导航到普通用户页面");
            intent = new Intent(LoginActivity.this, MainActivity.class);
        }

        Log.d(TAG, "即将启动新活动，用户类型=" + userType + ", 目标活动=" + intent.getComponent().getClassName());

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();

        new android.os.Handler(getMainLooper()).postDelayed(() -> {
            isNavigating = false;
        }, 1000);
    }

    private void navigateBasedOnUserType() {
        if (isNavigating) {
            Log.d(TAG, "已在导航过程中，避免重复导航");
            return;
        }

        isNavigating = true;

        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String userType = prefs.getString(KEY_USER_TYPE, USER_TYPE_USER);

        Log.d(TAG, "用户类型: " + userType + ", 准备导航");

        Intent intent;
        if (USER_TYPE_ADMIN.equals(userType)) {
            Log.d(TAG, "导航到管理员页面");
            intent = new Intent(LoginActivity.this, AdminActivity.class);
        } else {
            Log.d(TAG, "导航到普通用户页面");
            intent = new Intent(LoginActivity.this, MainActivity.class);
        }

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();

        new android.os.Handler(getMainLooper()).postDelayed(() -> {
            isNavigating = false;
        }, 1000);
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        progressBar = findViewById(R.id.progressBar);
        tvRegister = findViewById(R.id.tv_register);
        
        progressBar.setVisibility(View.GONE);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    private void loadRememberedCredentials() {
        SharedPreferences prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE);
        boolean rememberMe = prefs.getBoolean("remember_me", false);
        
        if (rememberMe) {
            String username = prefs.getString("remembered_username", "");
            String password = prefs.getString("remembered_password", "");
            
            if (!username.isEmpty()) {
                etUsername.setText(username);
                
                if (!password.isEmpty()) {
                    etPassword.setText(password);
                }
            }
        }
    }

    private void checkAutoLogin() {
        SharedPreferences prefs = getSharedPreferences("MyAppPrefs", MODE_PRIVATE);
        boolean autoLogin = prefs.getBoolean("auto_login", false);
        
        if (autoLogin) {
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();
            
            if (!username.isEmpty() && !password.isEmpty()) {
                Log.d(TAG, "开始自动登录");
                login();
            }
        }
    }
}